package com.mini.grpc.transport.netty;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http2.*;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslHandler;

/**
 * HTTP/2客户端连接初始化器
 */
public class Http2ClientInitializer extends ChannelInitializer<SocketChannel> {
    
    private final SslContext sslContext;
    private final NettyClientHandler clientHandler;
    
    public Http2ClientInitializer(SslContext sslContext, NettyClientHandler clientHandler) {
        this.sslContext = sslContext;
        this.clientHandler = clientHandler;
    }
    
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        
        if (sslContext != null) {
            SslHandler sslHandler = sslContext.newHandler(ch.alloc());
            pipeline.addLast(sslHandler);
        }
        
        // HTTP/2连接处理器
        Http2Connection connection = new DefaultHttp2Connection(false);
        Http2ConnectionEncoder encoder = new DefaultHttp2ConnectionEncoder(connection, new DefaultHttp2FrameWriter());
        Http2ConnectionDecoder decoder = new DefaultHttp2ConnectionDecoder(connection, encoder, new DefaultHttp2FrameReader());
        
        Http2Settings initialSettings = Http2Settings.defaultSettings();
        
        // 创建新的NettyClientHandler实例，因为它需要特定的decoder/encoder
        NettyClientHandler handler = new NettyClientHandler(decoder, encoder, initialSettings);
        handler.decoder().frameListener(handler);
        
        pipeline.addLast(handler);
    }
} 